<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    :inline-message="true"
  >
    <template v-if="rulesItem">
      <el-checkbox-group v-model="formData.checkedRulesItems" @change="onCheckedRulesItemsChange">
        <template v-for="dict in rulesItem.rulesItems" :key="dict.rulesItem">
          <el-checkbox :value="dict.rulesItem">
            {{ dict.rulesItemName }}
          </el-checkbox>
        </template>
      </el-checkbox-group>
      <div v-for="(item, index) in checkedRulesItems" :key="index">
        <template v-if="item.inputType == 'input_type_spinner' && item.rulesChildItems.length > 0">
          <el-form-item :label="item.rulesItemName" :key="index">
            <el-select
              v-model="formData[item.rulesItem]"
              placeholder="请选择规则"
              multiple
              clearable
            >
              <el-option
                v-for="dict in item.rulesChildItems"
                :key="dict.itemId"
                :label="dict.itemName"
                :value="dict.itemId"
              />
            </el-select>
          </el-form-item>
        </template>
        <template v-if="item.inputType == 'input_type_textbox' && item.rulesChildItems.length > 0">
          <el-form-item :label="item.rulesItemName" :key="index">
            <el-table :data="item.rulesChildItems">
              <el-table-column label="" prop="itemName" width="80px" />
              <el-table-column label="规则类型" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.itemType" class="w-80px" placeholder="请选择">
                    <el-option
                      :label="dict.typeName"
                      :value="dict.typeCode"
                      v-for="dict in rulesItem.rulesTypes"
                      :key="dict.typeCode"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="规则值" align="center">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.itemValue"
                    :min="0"
                    :disabled="!scope.row.itemType && scope.row.itemType != 0"
                    :precision="2"
                    :step="0.1"
                    class="w-100%"
                    :controls="false"
                  >
                    <template #suffix>
                      <span v-if="scope.row.itemType == 0">%</span>
                      <span v-else>个</span>
                    </template>
                  </el-input-number>
                  <!-- <el-input v-model="scope.row.itemValue">
                    <template #prepend>
                      <el-select v-model="scope.row.itemType" placeholder="请选择" class="w-100px!">
                        <el-option
                          :label="dict.typeName"
                          :value="dict.typeCode"
                          v-for="dict in rulesItem.rulesTypes"
                          :key="dict.typeCode"
                        />
                      </el-select>
                    </template>
                    <template #append>
                      <div class="w-10px">
                        <span v-if="scope.row.itemType == '0'"> % </span>
                        <span v-else> 个 </span>
                      </div>
                    </template>
                  </el-input> -->
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </template>
        <!-- <template v-if="item.inputType == 'input_type_select' && item.rulesChildItems.length == 0">
          <el-form-item>
            <div class="w-100%">
              <el-button @click="handleAddCoupon()">添加代金券</el-button>
              <CouponList
                v-model:multiple-selection="couponList"
                :is-detail="isDetail"
                class="mt-20px"
              >
                <template #extension>
                  <el-table-column align="center" label="关联数量" prop="number" min-width="168">
                    <template #default="{ row }">
                      <el-input-number
                        v-model="row.number"
                        :disabled="isDetail"
                        :min="0"
                        :precision="0"
                        :step="1"
                        class="w-120px!"
                        controls-position="right"
                      />
                    </template>
                  </el-table-column>
                </template>
              </CouponList>
            </div>
          </el-form-item>
        </template> -->
        <template v-if="item.inputType == 'input_type_select' && item.rulesChildItems.length > 0">
          <el-form-item :label="item.rulesItemName" :key="index">
            <el-table :data="item.rulesChildItems">
              <el-table-column label="" prop="itemName" width="120px" />
              <!-- <el-table-column label="优惠券" align="center">
                <template #default="scope">
                  <el-button
                    v-if="!scope.row.couponList || scope.row.couponList?.length == 0"
                    @click="handleAddCoupon(scope.row)"
                    >添加代金券</el-button
                  >
                  <el-popover placement="top" :width="800" trigger="click" v-else>
                    <template #reference>
                      <el-button>已关联{{ scope.row.couponList?.length }}张代金券</el-button>
                    </template>
                    <CouponList
                      v-model:multiple-selection="scope.row.couponList"
                      :is-detail="isDetail"
                      class="mt-20px"
                    >
                      <template #extension>
                        <el-table-column
                          align="center"
                          label="关联数量"
                          prop="number"
                          min-width="168"
                        >
                          <template #default="{ row }">
                            <el-input-number
                              v-model="row.number"
                              :disabled="isDetail"
                              :min="0"
                              :precision="0"
                              :step="1"
                              class="w-120px!"
                              :controls="false"
                              controls-position="right"
                            />
                          </template>
                        </el-table-column>
                      </template>
                    </CouponList>
                  </el-popover>
                </template>
              </el-table-column> -->
              <el-table-column label="关联商品" align="center">
                <template #default="scope">
                  {{ scope.row.giveGoods }}
                  <el-button
                    @click="openGiveGoodsForm('create', scope.row)"
                    v-if="!scope.row.giveGoods || scope.row.giveGoods?.length == 0"
                    >关联商品</el-button
                  >
                  <el-button @click="openGiveGoodsForm('update', scope.row)" type="primary" v-else
                    >已关联{{ scope.row.giveGoods.length }}件商品</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </template>
      </div>
    </template>
  </el-form>

  <CouponSelect
    ref="couponSelectDialog"
    v-model:multiple-selection="couponList"
    :take-type="CouponTemplateTakeTypeEnum.ADMIN.type"
  >
    <template #extension>
      <el-table-column align="center" label="关联数量" prop="number" min-width="168">
        <template #default="{ row }">
          <el-input-number
            v-model="row.number"
            :min="0"
            :precision="0"
            :step="1"
            class="w-120px!"
            controls-position="right"
          />
        </template>
      </el-table-column>
    </template>
  </CouponSelect>

  <!-- 关联商品弹窗 -->
  <GiveGoodsForm ref="GiveGoodsFormRef" @success="setGiveGoods" />
</template>
<script setup lang="ts">
import { RulesApi } from '@/api/system/rules'
import rules from '@/components/bpmnProcessDesigner/src/modules/rules'
import { propTypes } from '@/utils/propTypes'
import { CouponList } from '@/views/mall/product/spu/components/index'
import { GiveGoodsForm } from '@/views/mall/product/components/index'
const props = defineProps({
  rulesId: propTypes.string.def(undefined),
  rulesItem: propTypes.object.def({}), // 是否作为详情组件
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})
const formLoading = ref(false) // 表单的加载中
const formData = ref<any>({
  checkedRulesItems: []
})
const formRules = reactive({
  rulesId: [{ required: true, message: '规则ID不能为空', trigger: 'blur' }],
  rulesItem: [
    {
      required: true,
      message: '规则库-选项 0关闭 1普通会员 2付费会员 3标签不能为空',
      trigger: 'blur'
    }
  ],
  itemId: [
    { required: true, message: '标签ID；会员等级ID，标签ID，商品ID不能为空', trigger: 'blur' }
  ],
  sort: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态（0正常 1停用）不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    rulesItemId: undefined,
    rulesId: undefined,
    rulesItem: undefined,
    itemId: undefined,
    itemType: undefined,
    itemValue: undefined,
    sort: undefined,
    status: undefined,
    remark: undefined
  }
  row.rulesId = props.rulesId
  // formData.value.push(row)
}
/**优惠券功能 */
// 优惠券列表
import CouponSelect from '@/views/mall/promotion/coupon/components/CouponSelect.vue'
import * as CouponTemplateApi from '@/api/mall/promotion/coupon/couponTemplate'
import { CouponTemplateTakeTypeEnum } from '@/utils/constants'

const couponList = ref<CouponTemplateApi.CouponTemplateVO[]>([])
const couponSelectDialog = ref()
const operateRow = ref() //操作的行

// 添加优惠券
const handleAddCoupon = (row: any) => {
  operateRow.value = row

  couponSelectDialog.value.open()
}
/** 关联商品 */
const GiveGoodsFormRef = ref()
const openGiveGoodsForm = (type: string, row: any) => {
  if (!row.giveGoods) {
    row.giveGoods = []
  }
  operateRow.value = row
  GiveGoodsFormRef.value.open(type, row)
}
const setGiveGoods = (products: any) => {
  operateRow.value.giveGoods = products
}
watch(
  () => couponList.value,
  () => {
    operateRow.value['couponList'] = couponList.value
  }
)

const checkedRulesItems = ref()
const onCheckedRulesItemsChange = () => {
  checkedRulesItems.value = props.rulesItem.rulesItems.filter((ele) => {
    return formData.value.checkedRulesItems.includes(ele.rulesItem)
  })
  checkedRulesItems.value.forEach((ele) => {
    if (ele.inputType == 'input_type_spinner') {
    } else if (ele.inputType == 'input_type_textbox' || ele.inputType == 'input_type_select') {
      // 如果是输入就默认全选
      formData.value[ele.rulesItem] = ele.rulesChildItems.map((e) => {
        return e.itemId
      })
    }
  })
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  let data = [] as any
  formData.value.checkedRulesItems.forEach((checkedRulesItem) => {
    // 遍历所有选中的一级分类
    let nowcheckedRulesItemInfo = props.rulesItem.rulesItems.find((rulesItemInfo) => {
      return rulesItemInfo.rulesItem == checkedRulesItem
    }) //当前选择的信息
    console.log(formData.value[checkedRulesItem])
    formData.value[checkedRulesItem].forEach((formItemValue) => {
      // 遍历选中的对应的类型的值
      const row = {
        rulesItem: checkedRulesItem,
        itemId: formItemValue,
        itemValue: undefined,
        itemType: undefined,
        rulesId: props.rulesId
      }
      console.log(formItemValue)

      console.log(nowcheckedRulesItemInfo)
      // 根据当前选择的源数据信息和所选中的信息 进行匹配 有的输入类型在原数据信息中添加了
      nowcheckedRulesItemInfo.rulesChildItems.forEach((item) => {
        if (item.itemId == formItemValue) {
          row.itemValue = item.itemValue
          row.itemType = item.itemType
        }
      })

      data.push(row)
    })
  })

  return data
}
const setData = (rulesItems) => {
  rulesItems.forEach((ele) => {
    let checkedRulesItems = [] as any
    checkedRulesItems.push(ele.rulesItem)
    formData.value.checkedRulesItems = uniqueOrdered(checkedRulesItems)
    formData.value.checkedRulesItems.forEach((checkedRulesItem) => {
      let nowcheckedRulesItemInfo = props.rulesItem.rulesItems.find((rulesItemInfo) => {
        return rulesItemInfo.rulesItem == checkedRulesItem
      }) //当前选择的信息
      formData.value[checkedRulesItem] = [] as any
      if (ele.rulesItem == checkedRulesItem) {
        formData.value[checkedRulesItem].push(ele.itemId)
        formData.value[checkedRulesItem].forEach((formItemValue) => {
          nowcheckedRulesItemInfo.rulesChildItems.forEach((item) => {
            if (item.itemId == formItemValue) {
              item.itemValue = ele.itemValue
              item.itemType = ele.itemType
            }
          })
        })
      }
    })
  })
  onCheckedRulesItemsChange()
}
const uniqueOrdered = (arr) => {
  return [...new Set(arr)]
} /** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.rulesItem,
  async (val) => {
    // 1. 重置表单
    formData.value = {
      checkedRulesItems: []
    }
    checkedRulesItems.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return
    }
    try {
      formLoading.value = true
      // formData.value = await RulesApi.getRulesItemListByRulesId(val)
      // formData.value = props.rulesItem
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)
defineExpose({ validate, getData, setData })
</script>
